// 用来封装axios
import axios from 'axios'
import store from '@/store'
import router from '@/router'

const request = axios.create({
  baseURL: 'http://www.liulongbin.top:3008'
})

// 添加请求拦截器
request.interceptors.request.use(function (config) {
  // Do something before request is sent
  console.log(config)
  if (config.url.startsWith('/my')) {
    config.headers.Authorization = store.state.user.token
  }
  return config
}, function (error) {
  // Do something with request error
  return Promise.reject(error)
})

// 添加响应拦截器
request.interceptors.response.use(function (response) {
  // Any status code that lie within the range of 2xx cause this function to trigger
  // Do something with response data
  return response
}, function (error) {
  // Any status codes that falls outside the range of 2xx cause this function to trigger
  // Do something with response error
  if (error.response.status === 401) {
    store.commit('user/updateToken', '')
    store.commit('user/updateUser', {})
    // 跳转到登录页
    router.push('/login')
  }
  return Promise.reject(error)
})
export default request
